<template>
  <el-main style="width: 100%">
    <el-row class="margin-bottom-10">
      <el-col :span="20" class="mb10">
        <span class="text-size">工程名称:</span>
        <span class="text-size" style="padding-left: 10px;">{{ uploadform.engineeringName }}</span>
      </el-col>
      <el-col :span="20">
        <span class="text-size">委托单编号:</span>
        <span class="text-size">{{ uploadform.number }}</span>
      </el-col>
    </el-row>
    <el-row class="margin-bottom-10 mt20" v-for="(item, index) in list" :key="item.id">
      <el-col :span="5" class="text-size">附表({{ index + 1 }}):</el-col>
      <el-col :span="5">
        <a class="text-size" style="color:#1176FF" :download="item.name" :href="item.fileUrl">{{ item.name }}</a>
      </el-col>
      <el-col :span="5">
        <span class="detailbtn mr20" @click="onDetail(item.id)">详情</span>
        <!-- <span class="detailbtn" @click="delTable(item.id)">删除</span> -->
      </el-col>
    </el-row>
    <el-row class="margin-bottom-10">
      <el-col style="text-align: center;margin-top:15px" :span="15">
        <!-- <el-button type="primary" @click="uploadBtnlist">上传清单</el-button> -->
        <el-button @click="gobacks">返回</el-button>
      </el-col>
    </el-row>
    <!--上传附表 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="openTableDialog" width="600px"
      append-to-body>
      <el-form :inline="true" :model="uploadform" ref="uploadform">
        <el-row class="margin-bottom-10">
          <el-col :span="20" class="mb10">
            <span class="text-size">工程名称:</span>
            <span class="text-size">{{ uploadform.engineeringName }}</span>
          </el-col>
          <el-col :span="20">
            <span class="text-size">委托单编号:</span>
            <span class="text-size">{{ uploadform.number }}</span>
          </el-col>
        </el-row>

        <!-- <el-row class="margin-bottom-10">
          <el-col :span="24">

            <el-form-item label="文件名称" style="margin-bottom: 10px;">
              <el-input type="input" v-model="uploadform.name" style=""></el-input>
            </el-form-item>

          </el-col>
        </el-row> -->
        <el-row class="margin-bottom-10">
          <el-col :span="24">
            <!-- <el-form-item label="" style="margin-bottom: 10px;">
              <el-input type="input" v-model="uploadform.fileUrl" style="width: 230px;"></el-input>
            </el-form-item> -->
            <div v-if="!rowArr.businessType">
              <el-form-item label="业务类型" prop="ipaddr">
                <el-select v-model="uploadform.businessType" placeholder="请选择" @change="onchangeJC">
                  <el-option key="shiwai" label="室外检测" value="shiwai"></el-option>
                  <el-option key="shinei" label="室内检测" value="shinei"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- <div > -->
            <el-upload class="upload-demo" v-if="isbusinessType" :limit="1" accept=".xlsx, .xls" :action="uploadImgUrl"
              :headers="headers" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove"
              multiple :on-exceed="handleExceed" :file-list="fileList" :on-success="handleSuccess" drag
              style="display: inline-block; ">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip text-center" slot="tip">
                <div class="el-upload__tip" slot="tip">
                  <a :href="file1Url" download="室内表格.xlsx" style="list-style: none;color: #1176FF;">附表模版下载</a>
                  <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                  
                    @click="downloadFile1('室内表格.xlsx')">附表模版下载111</el-link> -->
                </div>
              </div>
            </el-upload>
            <!-- </div> -->
            <div v-if="nobusinessType">
              <div class="margin-bottom-10">
                <span>请先选择模版</span>
                <el-radio-group v-model="uploadform.type" @change="downloadfile" style="margin-left: 10px;">
                  <el-radio label="1">下载模板1</el-radio>
                  <el-radio label="2">下载模板2</el-radio>
                </el-radio-group>
              </div>

              <el-upload class="upload-demo" ref="upload" :data="{ type: uploadform.type, commissionId: rowArr.id }"
                :disabled="isdowntrue" :limit="1" accept=".xlsx, .xls" :headers="headers" :action="uploadImgUrl2"
                :on-success="handleFileSuccess" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                  <div class="el-upload__tip" slot="tip">

                    <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;margin-right: 10px;"
                      @click="downloadFile('../../../src/assets/download/室外检测附表导入模版1.xlsx', '室外检测附表导入模版1.xlsx')">下载模板1</el-link>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                      @click="downloadFile('../../../src/assets/download/室外检测附表导入模版2.xlsx', '室外检测附表导入模版2.xlsx')">下载模板2</el-link> -->
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>

                </div>
              </el-upload>
            </div>


          </el-col>

        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
    <!-- 附表详情 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="tabledetail" width="600px" append-to-body>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">工程名称:</span>
          <span class="text-size">{{ commissionOne.engineeringName }}</span>
        </el-col>
      </el-row>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">工程地点:</span>
          <span class="text-size">{{ commissionOne.address }}</span>
        </el-col>
      </el-row>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">建设单位:</span>
          <span class="text-size">{{ commissionOne.constructionUnit }}</span>
        </el-col>
      </el-row>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">监理单位:</span>
          <span class="text-size">{{ commissionOne.supervisionUnit }}</span>
        </el-col>
      </el-row>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">设计单位:</span>
          <span class="text-size">{{ commissionOne.designUnit }}</span>
        </el-col>
      </el-row>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">勘察单位:</span>
          <span class="text-size">{{ commissionOne.surveyUnit }}</span>
        </el-col>
      </el-row>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">施工单位:</span>
          <span class="text-size">{{ commissionOne.construcUnit }}</span>
        </el-col>
      </el-row>
      <div v-if="tableDetailobj.businessType == 'shinei'">
        <div v-if="tableDetailobj.sampleList">
          <div v-for="item in tableDetailobj.sampleList" :key="item.id">
            <div style="margin: 10px 0;">
              {{ detectionOptions[item.project] }}
              <span style="color: #1890ff;"> {{item.number}}</span>
             
            </div>
          </div>
        </div>
      </div>
      <!-- <el-row class="margin-bottom-10">
          <el-col :span="20">
            <span class="text-size">土样:</span>
            <span class="text-size">{{ tableDetailobj.soilSample }}</span>
          </el-col>
        </el-row>
        <el-row class="margin-bottom-10">
          <el-col :span="20">
            <span class="text-size">水样:</span>
            <span class="text-size">{{ tableDetailobj.waterSample }}</span>
          </el-col>
        </el-row>
        <el-row class="margin-bottom-10">
          <el-col :span="20">
            <span class="text-size">岩样:</span>
            <span class="text-size">{{ tableDetailobj.rockSample }}</span>
          </el-col>
        </el-row>
        <el-row class="margin-bottom-10">
          <el-col :span="20">
            <span class="text-size">水腐蚀:</span>
            <span class="text-size">{{ tableDetailobj.soilCorrosion }}</span>
          </el-col>
        </el-row>
      </div>
      <el-row class="margin-bottom-10">
        <el-col :span="20">
          <span class="text-size">施工单位:</span>
          <span class="text-size">{{ commissionOne.construcUnit }}</span>
        </el-col>
      </el-row> -->
      <div v-if="tableDetailobj.businessType == 'shiwai'">
        <el-table class="mt20" v-loading="loading" :data="tableDetailobj.attachedDataList"
          v-if="tableDetailobj.type == 1">
          <!-- <el-table-column type="selection" width="55" align="center" show-overflow-tooltip /> -->
          <el-table-column label="序号" align="center" prop="id" />
          <el-table-column label="桩号" align="center" prop="pileNumber" />
          <el-table-column label="桩型" align="center" prop="pileType" />
          <el-table-column label="桩长" align="center" prop="pileLength" />
          <el-table-column label="桩径(mm)" align="center" prop="diameter" />
          <el-table-column label="桩端持力层" align="center" prop="pileLayer" />
          <el-table-column label="砼强度" align="center" prop="goneStrength" />
          <el-table-column label="预估水平/抗压极限值(kN)" align="center" prop="compressionOne" />
          <el-table-column label="成桩日期" align="center" prop="pileDate" />
          <el-table-column label="实验方法(1~19)" align="center" prop="testMethod" />


          <!-- <el-table-column label="预估水平/抗拔极限值(K/N)" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type" />
        </template>
</el-table-column> -->

          <!-- <el-table-column label="操作" align="center" width="100%" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleAccept(scope.row)">受理</el-button>
            <el-button size="mini" type="text" @click="handleCollar(scope.row)">领样</el-button>
            <el-button size="mini" type="text" @click="handleReport(scope.row)">报告</el-button>
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
              v-hasPermi="['enterprise:enterprise:edit']">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['enterprise:enterprise:remove']">删除</el-button>
          </template>
        </el-table-column> -->
        </el-table>
        <el-table class="mt20" v-loading="loading" v-if="tableDetailobj.type == 2"
          :data="tableDetailobj.attachedDataList">
          <el-table-column label="模版类型" align="center" prop="type">
            <template slot-scope="scope">
              <span v-if="scope.row.type == 1">模版1</span>
              <span v-if="scope.row.type == 2">模版2</span>
            </template>
          </el-table-column>
          <el-table-column label="试验号" align="center" prop="testNumber" />
          <el-table-column label="位置" align="center" prop="position" />

          <el-table-column label="持力层" align="center" prop="bearingStratum" />

          <el-table-column label="预估承载力极限值(kN)" align="center" prop="bearingValue" />
          <el-table-column label="施工日期" align="center" prop="constructionTime" />
          <el-table-column label="试验方法" align="center" prop="testMethod" />
        </el-table>
      </div>
    </el-dialog>
  </el-main>
</template>

<script>
import file1Url from '@/assets/download/室内表格.xlsx';

import { getToken } from "@/utils/auth";
import {
  getAttachedList,
  uploadTable, getAttachedDetail, delAttached, Delattachedlist
} from "@/api/enterprise/enterprise";

export default {
  data() {
    return {
      file1Url,
      detectionOptions: [],
      shineiVal: '',
      isdowntrue: true,
      loading: false,
      tableDetailobj: {},
      commissionOne: {},
      isbusinessType: false,
      nobusinessType: false,
      uploadform: {
        id: '',
        name: '',
        fileUrl: '',
        commissionId: '',
        soilCorrosion: '',
        soilSample: '',
        waterSample: '',
        rockSample: '',
        businessType: ''

      },
      openTableDialog: false,
      name1: "",
      title: '',
      filename: "",
      fileList: [],
      tabledetail: false,
      tableList: [],
      list: [],
      rowArr: {},
      fileList: [],
      uploadImgUrl2: process.env.VUE_APP_BASE_API + "/attached/attached/importData", //室外检测上传
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/attached/attached/importDataNie", // //室内检测上传
      //uploadImgUrl:process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },

    };
  },
  created() {
    this.rowArr = JSON.parse(this.$route.query.row)
    console.log('rowArr', this.rowArr)
    this.uploadform.engineeringName = this.rowArr.engineeringName
    this.uploadform.number = this.rowArr.number
    this.onchangeJC(this.rowArr.businessType);
    this.getList()
    //室内字典
    this.getDicts("detection_item_indoor").then(response => {
      let data = response.data
      let new_arr = [];
      data.forEach(function (item) {
        new_arr[item.dictValue] = item.dictLabel
      });
      this.detectionOptions = new_arr;
    });
  },
  methods: {
    //上传附表清单
    onSubmit() {
      this.uploadform.commissionId = this.rowArr.id
      if (this.shineiVal == 'shinei') {
        //this.uploadform.businessType = this.rowArr.businessType
        uploadTable(this.uploadform).then(res => {
          this.$message.success(`上传成功`)
          this.openTableDialog = false
          this.getList()
          this.resetForm1()
        })
        return
      }
      this.openTableDialog = false


    },
    //删除附表
    delTable(id) {
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function () {
          return delAttached(id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });

    },
    onchangeJC(val) {
      this.shineiVal = val
      if (val == 'shinei') {
        this.nobusinessType = false
        this.isbusinessType = true
      }
      if (val == 'shiwai') {
        this.nobusinessType = true
        this.isbusinessType = false
      }

    },
    getList() {
      let _this = this
      let commissionId = this.rowArr.id
      getAttachedList({ commissionId: commissionId }).then(res => {
        this.list = res.rows
      })
    },

    // 表单重置
    resetForm1() {
      this.uploadform = {
        id: '',
        commissionId: '',
        name: '',
        fileUrl: '',
        businessType: '',
        soilSample: '',
        waterSample: '',
        rockSample: '',
        soilCorrosion: ''
      };
      this.resetForm("uploadform");
    },
    uploadBtnlist() {


      this.openTableDialog = true
      this.title = '上传附表'
      // uploadTable(this.uploadform.then(res => {
      //   // this.getList()

      //   this.resetForm1()
      // })



      //this.$router.push({ name: "uploadTable" });
    },
    gobacks() {
      this.$router.go(-1);
    },
    cancel() {
      this.openTableDialog = false
    },
    /** 查询企业信息列表 */
    // getList() {
    //   this.loading = true;
    //   listEnterprise(this.queryParams).then(response => {
    //     this.enterpriseList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   });
    // },
    // closebtn(){
    //   this.$emit('closeTableDialog')
    // },
    handleFileUploadProgress() {

    },
    // 文件上传成功处理
    handleFileSuccess(res, file, fileList) {
      console.log(res, file)
      this.getList()
      this.$message.success(`上传成功`)
      // this.uploadform.name = res.data.fileInfo.originalFilename
      // this.uploadform.fileUrl = res.data.fileInfo.url
    },
    handleSuccess(res) {
      this.uploadform.name = res.data.fileInfo.originalFilename
      this.uploadform.fileUrl = res.data.fileInfo.url
      this.uploadform.soilSample = res.data.sampleList.tuyang_num
      this.uploadform.waterSample = res.data.sampleList.shuiyang_num
      this.uploadform.rockSample = res.data.sampleList.yanyang_num
      this.uploadform.soilCorrosion = res.data.sampleList.tufushi_num

      console.log(this.uploadform, 'res')
    },
    //选中模版
    downloadfile(val) {
      console.log(val, 'val')
      if (val == 1) {
        const link = document.createElement("a");
        link.download = '室外检测附表导入（模版1）.xlsx' || "download";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.isdowntrue = false
      } else {
        const link = document.createElement("a");
        link.download = '室外检测附表导入（模版2）.xlsx' || "download";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.isdowntrue = false
      }
    },
    downloadFile1(filename) {
       // 使用require确保webpack能正确处理路径
      // const link = document.createElement("a");
      // link.href = '/document/室内表格.xlsx';
      // link.download = '室内表格.xlsx';
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
       // 修改为使用绝对路径或确保路径正确
       // 使用fetch API确保完整下载

    fetch('/document/室内表格.xlsx', {
      headers: {
        'Accept-Encoding': 'identity'  // 禁用压缩
      }
    })
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename || 'shinei.xlsx';
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
    })
    .catch(err => console.error('下载失败:', err));
  
    },
    //附表详情
    onDetail(id) {
      getAttachedDetail(id).then(res => {
        this.tableDetailobj = res.data
        this.commissionOne = res.data.commissionOne
      })
      this.title = '附表详情'
      this.tabledetail = true
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      // Delattachedlist().then(res=>{
      //   this.$message.success(`删除成功`)
      // })
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  }
};
</script>

<style lang="scss" scoped>
.text-size {
  font-size: 14px;
  color: #606266;
}

.margin-bottom-10 {
  margin-bottom: 10px;
}

.detailbtn {
  font-size: 14px;
  color: #2b84fb;
  cursor: pointer;
}
</style>